package net.jueb.custom.client;

import net.jueb.custom.pojo.NError;
import net.jueb.custom.pojo.NMsg;
import net.jueb.custom.protocol.SProtocolType;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory;

public class ClientHandler extends ChannelHandlerAdapter{
	InternalLogger log=Log4JLoggerFactory.getInstance(this.getClass());
	StringBuffer sb=new StringBuffer();
	byte[] data;
	{
		sb.append("a");
		for(int i=0;i<=23;i++)
		{
			sb.append(sb.toString());
		}
		data=sb.toString().getBytes();
		log.info("data构建完成，大小："+data.length);
	}
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		NMsg nmsg=new NMsg(SProtocolType.Serizable, "request", data);
//		System.out.println(nmsg.toString());
		for(int i=1;i<=10;i++)
		{
			ctx.writeAndFlush(nmsg);
			log.info("client nmsg is write,count="+i);
		}
		
	}
	
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)throws Exception {
		if(msg instanceof NError)
		{
			NError error=(NError)msg;
			log.error(error.toString());
			return ;
		}
		
		NMsg nmsg=(NMsg)(msg);
		if(nmsg==null)
		{
			return;
		}
		log.info("收到服务端回复："+nmsg.toString());
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
}
